<?php

namespace app\index\service;

use app\common\model\ToolModel;
use app\index\model\HandoverModel;
use app\index\model\NewskuModel;
use app\index\model\UserModel;

class HandoverService
{
    static public $status = [
        1 => '待审核',
        2 => '已驳回',
        3 => '待制作',
        4 => '已制作',
        5 => '已完成',
    ];
    //制作类型 0样品 1资料包
    static public $type=[
        1=>'资料包',
        2=>'样品'
    ];

    static public function getHandoverList($param)
    {
        $titles = [
            'creation_time'=>'交接日期',
            'developer_name'=>'开发人员',
            'spu'=>'SPU',
            'sku'=>'SKU',
            'quantity'=>'销售数量',
            'quantity_unit'=>'销售单位',
            'type'=>'交接类型',
            'production_type_str'=>'制作类型',
            'production_type_num'=>'样品数量',
            'imitation'=>'仿品（具体品牌）',
            'realpic'=>'盗图/实拍图',
            'authorization_str'=>'是否授权',
            'logo' =>'品牌logo',
            'battery_str'   =>'带电池',
            'bulk'        =>'容量/体积',
            'bulk_unit'      =>'容量单位/体积单位',
            'ztlwh'     =>'主体尺寸长*宽*高',
            'zdlwh'     =>'自带包装长*宽*高',
            'packaging_film_str'     =>'包装拍摄',
            'research_links'     =>'调研链接',
            'develop_link'    =>'开发链接',
            'remarks'    =>'备注',
        ];
        return HandoverModel::getHandoverList($param, $titles, "\app\index\service\HandoverService::getHandoverListHandle");
    }
    static public function getHandoverListHandle($data)
    {
        $skuArr=array_column($data, 'sku');
        $develop = UserModel::getUserById(array_column($data, 'developer'));
        $sku = NewskuModel::getSkuBySku($skuArr);
        $assign=ToolModel::select('manage_assign',['sku'=>['in',$skuArr]],'edit_grade,img_grade,sku','','sku');
        $editaudit=ToolModel::select('manage_edit_audit',['sku'=>['in',$skuArr]],'audit_status','','sku');
        foreach ($data as &$v) {
            $v['status_str']=self::$status[$v['status']]??'';
            $v['developer_name'] = $develop[$v['developer']] ?? '';
            $v['sku_name']=$sku[$v['sku']]??'';
            $v['bulk_unit']=strtoupper($v['bulk_unit']);
            //$v['develop_link']=$link[$v['sku']]??'';
            $v['battery_str']=$v['battery']==1?'带':'不带';
            $v['authorization_str']=$v['authorization']==1?'已授权':'不授权';
            $v['packaging_film_str']=$v['battery']==1?'拍摄':'不拍摄';
            $v['production_type_str']=self::$type[$v['production_type']]??'';
            $v['length_str']=$v['length'];
            $v['ztlwh']="{$v['length']}*{$v['wide']}*{$v['hight']}";
            $v['zdlwh']="{$v['aslength']}*{$v['aswide']}*{$v['ashight']}";
            if(!empty($assign[$v['sku']])){
                $v['img_grade']=$assign[$v['sku']]['img_grade']??'';
                $v['edit_grade']=$assign[$v['sku']]['edit_grade']??'';
            }else{
                $v['img_grade']='';
                $v['edit_grade']='';
            }
            $v['editstatus']=((isset($editaudit[$v['sku']])&&$editaudit[$v['sku']]==2)||$v['status']==5)?0:1;
            unset($v['length']);
        }
        return $data;
    }
    static public function edit($param)
    {

        $sku=$param['sku'];
        $info=ToolModel::find('sku_handover',['sku'=>$param['sku']]);
        if(empty($info)){
            return returnArr(2,'sku不存在!');
        }
        if($info['status'] >= 3){
            return returnArr(2,'该状态不允许修改!');
        }
        $data =$param;
        $data['length']=$data['length_str'];
        unset($data['sku'],$data['sku_name'],$data['spu'],$data['s'],$data['length_str']);
        $data['status']=1;//变为待审核
        $data['modification_operator']=CN_NAME;
        if(ToolModel::updateData(['sku' => $sku], $data, 'sku_handover') && $info['status'] == 2){
            ToolModel::updateData(['sku' => $sku], ['status'=>1], 'manage_manufacture_audit');
        }
        ToolModel::updateData(['sku' => $sku], ['type'=>$data['production_type']], 'manage_manufacture_audit');
        return returnArr();
    }
    static public function getImg($skusAll){
        $skuArr=array_chunk($skusAll,1000);
        $data=[];
        foreach ($skuArr as $skus){
            if(!is_array($skus) || empty($skus)){
                return [];
            }
            $url = "http://192.168.5.207:9991/data/tuku/batchQuery";
            $list = [];
            foreach ($skus as $k => $sku) {
                $list[] = ['sku'=>$sku,'tuku'=>1,'type'=>null];
            }
            $params['skuList'] = json_encode($list);
            $result = curl($url, $params,'','POST',15,false);
            if(empty($result)){
                $result = curl($url, $params,'','POST',15,false);
            }
            if(empty($result)){
                $result = curl($url, $params,'','POST',15,false);
            }
            $result = json_decode($result,TRUE);

            if(!empty($result) && is_array($result)){
                foreach($result AS $imgarr){
                    foreach($imgarr AS $k => $v){
                        if(!empty($v)){
                            $sku = strtoupper(substr($k,0,-2));
                            $data[$sku]=1;
                        }
                    }
                }
            }
        }
        return $data;
    }
    //上传sku交接信息
    static public function uploadAdd($data, $param)
    {
        $error = [];
        $skuArr=array_column($data, '0');
        $skus =ToolModel::select('skus',['sku'=>['in',$skuArr]],'id','','sku');
        $developer=ToolModel::select('sku_attribute',['sku'=>['in',$skuArr]],'developer','','sku');
        $isSku=ToolModel::select('sku_handover',['sku'=>['in',$skuArr],'status'=>['<>',2]],'id','','sku');

        $rule1=ToolModel::find('setting_product_rule',['id'=>1,'status'=>1]);
        if(!empty($rule1)){
            $ruleType=explode(',',$rule1['describe']);
        }
        $rule2=ToolModel::find('setting_product_rule',['id'=>2,'status'=>1]);
        $skuImg=self::getImg($skuArr);
        $name = $param['cn_name'];
        $data1=[];
        $data2=[];
        $isSkuArr=[];//重复
        foreach ($data as $v) {
            $sku=$v[0];
            if (empty($skus[$sku])) {
                $error[] = "SKU: {$sku} 没录入,请录入后再交接!  ";
            }
            if(!empty($isSku[$sku])){
                $error[] = "SKU: {$sku} 已经导入过了!  ";
            }else{
                if(!empty($skuImg[$sku])){
                    $error[] = "SKU: {$sku} 已经有图,不允许再交接请走老品流程!  ";
                }
            }
            if(in_array($sku,$isSkuArr)){
                $error[] = "SKU: {$sku} 在上传文件里有重复!  ";
            }
            $isSkuArr[]=$sku;
            $temp=[];
            $temp['sku']=$sku;
            $temp['quantity']=$v[1];
            $temp['quantity_unit']=$v[2];
            $temp['type']=$v[3];
            $temp['production_type']=$v[4];
            $temp['production_type_num']=$v[5];


            $temp['imitation']=$v[6];
            $temp['realpic']=$v[7];//盗图/实拍图


            $temp['authorization']=$v[8];
            $temp['logo']=$v[9];
            $temp['battery']=$v[10];
            $temp['bulk']=$v[11];
            $temp['bulk_unit']=$v[12];

            $ztlwh=$v[13];//主体长宽高



            $lwh=$v[14];//自带长宽高


            $temp['packaging_film']=$v[15];
            $temp['research_links']=$v[16];
            $temp['develop_link']=$v[17];
            $temp['remarks']=$v[18];
            if($temp['production_type']=='样品'){
                if (!empty($temp['production_type_num'])&&!preg_match('/^[1-9][0-9]*$/', $temp['production_type_num'])) {
                    $error[] = "sku: {$sku} 样品数量必须为正整数!  ";
                }
            }
            foreach ($v as $k2 => $v2) {
                if (!in_array($k2,[13,15,16,18,5,6,11]) && empty($v2)) {
                    $error[] = "sku: {$sku}  除了仿品 主体尺寸 容量 样品数量 调研链接 包装拍摄 备注,   其他都要必填!";
                }
            }
            $lwh=explode('*', $lwh);
            if(count($lwh)!=3){
                $error[] = "sku: {$sku} 自带包装长*宽*高格式应为 1*1*1 ";
            }
            if(!empty($lwh[0])){
                $temp['aslength']=$lwh[0];
            }else{
                $temp['aslength']=0;
            }
            if(!empty($lwh[1])){
                $temp['aswide']=$lwh[1];
            }else{
                $temp['aswide']=0;
            }
            if(!empty($lwh[2])){
                $temp['ashight']=$lwh[2];
            }else{
                $temp['ashight']=0;
            }

            $lwh=explode('*', $ztlwh);
            if(!empty($lwh[0])){
                $temp['length']=$lwh[0];
            }else{
                $temp['length']=0;
            }
            if(!empty($lwh[1])){
                $temp['wide']=$lwh[1];
            }else{
                $temp['wide']=0;
            }
            if(!empty($lwh[2])){
                $temp['hight']=$lwh[2];
            }else{
                $temp['hight']=0;
            }


            if (!preg_match('/^[1-9][0-9]*$/', $temp['quantity'])) {
                $error[] = "sku: {$sku} 销售数量必须为正整数!  ";
            }
            if (!empty($temp['bulk'])&&!preg_match('/^[1-9][0-9]*$/', $temp['bulk'])) {
                //$error[] = "sku: {$sku} 容量体积必须为正整数!  ";
            }
            if (!preg_match('/^[1-9][0-9]*$/', $temp['aslength'])) {
                $error[] = "sku: {$sku} 自带包装长必须为正整数!  ";
            }
            if (!preg_match('/^[1-9][0-9]*$/', $temp['aswide'])) {
                $error[] = "sku: {$sku} 自带包装宽必须为正整数!  ";
            }
            if (!preg_match('/^[1-9][0-9]*$/', $temp['ashight'])) {
                $error[] = "sku: {$sku} 自带包装高必须为正整数!  ";
            }
            if (!empty($temp['length'])&&!preg_match('/^[1-9][0-9]*$/', $temp['length'])) {
                $error[] = "sku: {$sku} 主体长必须为正整数!  ";
            }
            if (!empty($temp['wide'])&&!preg_match('/^[1-9][0-9]*$/', $temp['wide'])) {
                $error[] = "sku: {$sku} 主体宽必须为正整数!  ";
            }
            if (!empty($temp['hight'])&&!preg_match('/^[1-9][0-9]*$/', $temp['hight'])) {
                $error[] = "sku: {$sku} 主体高必须为正整数!  ";
            }
            if(!empty($temp['bulk_unit'])&&!in_array(strtolower($temp['bulk_unit']),['ml','mah'])){
                $error[] = "sku: {$sku} 容量体积单位只能是 ML或MAH!  ";
            }


            if(!in_array($temp['realpic'],['盗图','实拍图'])){
                $error[] = "sku: {$sku} 盗图/实拍图只能是 盗图或实拍图!  ";
            }

            $authorization=['授权'=>1,'不授权'=>0];
            $temp['authorization']=$authorization[$temp['authorization']]??null;
            if(is_null($temp['authorization'])){
                $error[] = "sku: {$sku} 是否授权只能是 授权或不授权!  ";
            }
            $battery=['带'=>1,'不带'=>0];
            $temp['battery']=$battery[$temp['battery']]??null;
            if(is_null($temp['battery'])){
                $error[] = "sku: {$sku} 是否带电池只能是 带或不带!  ";
            }
            $production_type=['资料包'=>1,'样品'=>2];
            $temp['production_type']=$production_type[$temp['production_type']]??null;
            if(is_null($temp['production_type'])){
                $error[] = "sku: {$sku} 制作类型只能是 资料包或样品!  ";
            }
            $packaging_film=['拍摄'=>1,'不拍摄'=>0];
            $temp['packaging_film']=$packaging_film[$temp['packaging_film']]??null;
            if(is_null($temp['packaging_film'])){
                $error[] = "sku: {$sku} 包装拍摄只能是 拍摄或不拍摄!  ";
            }
            //判断是否交接类型 审核通过
            if(!empty($ruleType)){
                if(!in_array($temp['type'],$ruleType)){
                    $error[] = "sku: {$sku} 交接类型不是 ".join('、',$ruleType)." 不允许上传!  ";
                }
            }
            if(!empty($rule2)){
                if($rule2['make_type']==1){
                    //资料包
                    if($temp['production_type']==1){
                        $error[] = "sku: {$sku} 制作类型是资料包 不允许上传!  ";
                    }
                }else{
                    if(self::symbol($temp['production_type_num'],$rule2['symbol'],$rule2['num'])){
                        $error[] = "sku: {$sku} 制作类型样品数量{$rule2['symbol']} {$rule2['num']} 不允许上传 !  ";
                    }
                }
            }

            $temp['creation_time']=TIME;
            $temp['status']=1;
            $temp['modification_operator']=$name;
            $temp['spu']=$skus[$sku]??'';
            $temp['developer']=$developer[$sku]??'';
            $temp['modification_operator']=$name;
            $data1[]=$temp;
            $data2[]=['sku'=>$sku,'status'=>1,'type'=>$temp['production_type']];
        }
        unset($skus,$developer,$isSku,$data);
        //错误信息输出
        if (!empty($error)) {
            return returnArr(2, '',$error);
        }
        ToolModel::dbInsertOrUpdate('sku_handover',$data1);
        ToolModel::dbInsertOrUpdate('manage_manufacture_audit',$data2);
        return returnArr();
    }
    static public function symbol($a,$b,$c){
        if($b=='='){
            return $a==$c;
        }elseif ($b=='>'){
            return $a>$c;
        }elseif ($b=='<'){
            return $a<$c;
        }elseif ($b=='<='){
            return $a<=$c;
        }elseif ($b=='>='){
            return $a>=$c;
        }else{
            return false;
        }
    }
}